package com.example.mycomponent.component.wheelpicker

import android.annotation.SuppressLint
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import java.time.LocalDateTime

interface TimeWheelPickerState {
    var initialHour: Int
    var initialMinute: Int

    fun toTimeString(): String
}

@Composable
fun rememberTimeWheelPickerState(
    initialHour: Int? = null,
    initialMinute: Int? = null
): TimeWheelPickerState {
    return rememberSaveable(
        saver = TimeWheelPickerStateImpl.Saver()
    ) {
        TimeWheelPickerStateImpl(initialHour, initialMinute)
    }
}

private class TimeWheelPickerStateImpl (
    initialHour: Int?,
    initialMinute: Int?
) : TimeWheelPickerState {
    private var _hour = mutableIntStateOf(
        if (initialHour == null || initialHour > 23 || initialHour < 0) {
            LocalDateTime.now().hour
        } else {
            initialHour
        }
    )
    override var initialHour: Int
        get() = _hour.intValue
        set(value) {
            _hour.intValue = value
        }

    private var _minute = mutableIntStateOf(
        if (initialMinute == null || initialMinute > 59 || initialMinute < 0) {
            LocalDateTime.now().minute
        } else {
            initialMinute
        }
    )
    override var initialMinute: Int
        get() = _minute.intValue
        set(value) {
            _minute.intValue = value
        }

    @SuppressLint("DefaultLocale")
    override fun toTimeString(): String {
        return String.format("%02d:%02d", _hour.intValue, _minute.intValue)
    }

    companion object {
        fun Saver(): Saver<TimeWheelPickerStateImpl, Any> = listSaver(
            save = {
                listOf(
                    it.initialHour,
                    it.initialMinute
                )
            },
            restore = {
                TimeWheelPickerStateImpl(
                    initialHour = it[0],
                    initialMinute = it[1]
                )
            }
        )
    }
}
